<?php

namespace app\models;

use app\helpers\Upload;
use Yii;
use yii\base\Model;

/**
 * LoginForm is the model behind the login form.
 *
 * @property-read User|null $user This property is read-only.
 *
 */
class UploadForm extends Model
{
    public $pic_data;
    public $pic_url;
    public $image;
    public $ext;

    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            // username and password are both required
            [['pic_data', 'ext'], 'required'],
            ['pic_data', 'validatePicData']
        ];
    }

    public function attributeLabels()
    {

        return [
            'pic_data'=>Yii::t('app','Pic Data'),
            'ext'=>Yii::t('app','Ext')
        ]; // TODO: Change the autogenerated stub
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePicData($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $image = base64_decode(preg_replace('/^(data:\s*image\/(\w+);base64,)/', '', $this->pic_data));

            if ($image) {
                $this->image = $image;
            } else {
                $this->addError($attribute, '需要base64格式的数据');
            }
        }
    }

    public function upload()
    {
        if (!$this->validate()) {
            return false;
        }

        $file_name = Upload::uploadtofile($this->image, $this->ext);

        return $file_name;
    }
}
